// pages/moments/moments.js
Page({
  data: {
    moments: []
  },

  onLoad: function() {
    this.fetchMoments();
  },

  fetchMoments: function() {
    const that = this;
    wx.cloud.callFunction({
      name: 'getMoments',
      success: res => {
        if (res.result.success) {
          that.setData({
            moments: res.result.data
          });
        } else {
          wx.showToast({
            title: '获取朋友圈动态失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.showToast({
          title: '获取朋友圈动态失败',
          icon: 'none'
        });
        console.error('调用失败', err);
      }
    });
  },

  likeMoment: function(e) {
    const momentId = e.currentTarget.dataset.id;
    const likes = parseInt(e.currentTarget.dataset.likes, 10);
    wx.cloud.callFunction({
      name: 'likeMoments',
      data: { momentId },
      success: res => {
        if (res.result.success) {
          this.fetchMoments(); // 重新获取动态
          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          });
          this.fetchMoments(); // 重新获取动态
        } else {
          wx.showToast({
            title: '点赞失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.showToast({
          title: '点赞失败',
          icon: 'none'
        });
        console.error('点赞失败', err);
      }
    });
  },

  goToNewMoment: function() {
    wx.navigateTo({
      url: '/pages/postmoments/postmoments'
    });
  }
});